package com.aps.apspda.base;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.KeyEvent;
import android.widget.EditText;
import android.widget.Toast;

import com.aps.apspda.callback.CommonCallback;
import com.aps.apspda.entity.BaseEntity;
import com.aps.apspda.utils.ActivityManager;
import com.aps.apspda.utils.AppUtils;
import com.aps.apspda.utils.ToastUtils;

import java.util.List;

import butterknife.ButterKnife;

/**
 * @author jaxhuang
 * @date 2017/9/15
 * @desc
 */

public abstract class BaseActivity<T> extends AppCompatActivity {
    private EditText editText;
    private String eid;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ActivityManager.getActivityManager().addActivity(this);
        // 初始化布局
        if (getLayoutResId() != 0)
            setContentView(getLayoutResId());
        ButterKnife.bind(this);
        eid = getIntent().getStringExtra("eqpID");
        initView();
        initData();
    }

    protected abstract int getLayoutResId();

    protected abstract void initView();

    protected abstract void initData();

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ToastUtils.cancel();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == 138 || keyCode == 240 || keyCode == 241 || keyCode == 242) && editText != null && event.getAction() == KeyEvent.ACTION_DOWN) {
            editText.setText("");
            editText.requestFocus();
        }
        return super.onKeyDown(keyCode, event);
    }

    protected void setCallback(EditText editText) {
        this.editText = editText;
    }

    protected void loadSuccess(BaseEntity<List<T>> entity, CommonCallback commonCallback) {
        if (entity.isSuccess(this)) {
            commonCallback.onSuccess();
        } else {
            ToastUtils.showFreeToast(entity.getMessage(), this, false, Toast.LENGTH_SHORT);
        }
    }

    protected void loadError(Throwable e, String method) {
        AppUtils.saveErrorMessages(e, method);
        ToastUtils.showFreeToast("连接服务器失败",
                this, false, Toast.LENGTH_SHORT);
    }

    protected String getEqpID() {
        return eid.length() > 0 ? eid : getIntent().getStringExtra("eqpID");
    }
}
